package com.diana.common;

import redis.clients.jedis.Jedis;

import java.util.Collections;

/**
 * redis实现分布式锁
 */
public class RedisLock {

    private static final String LOCK_SUCCESS = "OK";
    private static final String SET_IF_NOT_EXIST = "NX";
    private static final String SET_WITH_EXPIRE_TIME = "PX";
    private static final String SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
    private static final Long RELEASE_SUCCESS = 1L;

    /**
     * 释放分布式锁
     * @param lockKey 锁 比如 user_id
     * @param requestId 请求标识 获取所的时候的uuid
     * @return 是否释放成功
     */
    public static boolean releaseRedisLock(String lockKey, String requestId) {
        Jedis jedis = JedisUtils.getJedis();
        Object result = jedis.eval(SCRIPT, Collections.singletonList(lockKey), Collections.singletonList(requestId));
        if (RELEASE_SUCCESS.equals(result)) {
            jedis.close();
            return true;
        }
        jedis.close();
        return false;
    }

    /**
     * 尝试获取分布式锁
     * @param lockKey 锁  比如user_id
     * @param requestId 请求标识 比如  uuid
     * @param expireTime 超期时间
     * @return 是否获取成功
     */
    public static boolean tryRedisLock( String lockKey, String requestId,int expireTime) {
        Jedis jedis = JedisUtils.getJedis();
        String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            jedis.close();
            return true;
        }
        jedis.close();
        return false;
    }
}
